<?php

namespace app\job;

use think\queue\Job;
use think\facade\Db;
use app\common\model\Order;
use app\service\order\OrderOper;

class OrderAutoOper extends BaseJob
{
    //自动取消订单
    public function autoClose(Job $job, $data)
    {
        if ($job->attempts() > 1) {
            return;
        }
        try {
            $order = $data['order'];
            if ($order) {
                Db::transaction(function () use ($order, $data) {
                    // 重新查询订单
                    $order = Order::where('status', 0)
                    ->where('id', $order['id'])
                    ->lock(true)
                    ->find();
                    // 执行关闭
                    $orderOper = new OrderOper();
                    $orderOper->cancel($order, null, $type = 'system', '自动取消订单');
                });
            }
            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            $job->delete();
            \think\facade\Log::record('订单自动关闭error'.$e->getMessage());
        }
    }

}
